define(function(require , exports , module){
	require("treetable-css");
	require("treetable");


	angular.module("uiTreetable" , [])
	.directive('uiTreetable' , ["$http" , "$timeout" , "baseService" , function($http , $timeout , baseService){
		return {
			restrict: 'A',
			replace: true,
			link:function($scope ,  $element , $attrs){
				var url = $attrs["url"];
				if (url) {
			 	  	baseService.request(url , "GET")
				  	.then(function(data){
						if (data) {
							$scope.list = transformData(data);
							$timeout(function(){
								$element.treetable({expandable:true});
							});
						}
						else {
							$scope.list =[];
						}
				  	});						
				}
			}
		};
	}]);

	function transformData(menus) {
		var i,l,
		key = "id",
		parentKey = "parentId",
		childKey = "childs";
		if (!key || key=="" || !menus) return [];
		var r = [];
		var tmpMap = [];
		for (i=0, l=menus.length; i<l; i++) {
			tmpMap[menus[i][key]] = menus[i];
			//routeMenu(menus[i] , $routeProvider);
		}
		for (i=0, l=menus.length; i<l; i++) {
			if (tmpMap[menus[i][parentKey]] && menus[i][key] != menus[i][parentKey]) {
				if (!tmpMap[menus[i][parentKey]][childKey])
					tmpMap[menus[i][parentKey]][childKey] = [];
				tmpMap[menus[i][parentKey]][childKey].push(menus[i]);
			} else {
				r.push(menus[i]);
			}
		}
		var result = [];
		for (var i = 0,len = r.length;i < len; i++) {
			reloadData(result , r[i]);
		}
		return result;
	};

	function reloadData(result , tree) {
		result.push(tree);
		if (tree.childs) {
			for (var i = 0, len = tree.childs.length;i < len;i++) {
				reloadData(result , tree.childs[i]);
			}
		}
	};
});
